import React, { useEffect, useImperativeHandle, useState } from 'react'
import { Form, Input, Modal, Select, TreeSelect, message } from 'antd'
import { IModalProps, ModelAction } from '@/types/modal'
import { getAllUserList } from '@/api/user'
import { createDept, editDept, getDeptList } from '@/api/dept'
import { IDeptItem } from '@/types/dept'
import { IUserItem } from '@/types/user'

const CreateDept: React.FC<IModalProps<IDeptItem>> = props => {
  const [action, setAction] = useState<ModelAction>('create')
  const [visiable, setVisiable] = useState(false)
  const [form] = Form.useForm()
  const [deptList, setDeptList] = useState<IDeptItem[]>([])
  const [userList, setUserList] = useState<IUserItem[]>([])

  // 自定义mRef,将open方法暴露给父组件使用
  useImperativeHandle(props.mRef, () => {
    return {
      open
    }
  })

  useEffect(() => {
    getAllUser()
  }, [])

  const getAllUser = async () => {
    const res = await getAllUserList()
    setUserList(res.data)
  }

  /**
   * 获取部门
   */
  const getAllDeptList = async () => {
    const { data } = await getDeptList()
    setDeptList(data)
  }
  // 显示
  const open = (type: ModelAction, data?: IDeptItem | { parentId: string }) => {
    console.log('open:', type, data)
    getAllDeptList()
    if (data) {
      form.setFieldsValue(data)
    }
    setAction(type)
    setVisiable(true)
  }

  // 提交
  const handleSubmit = () => {
    form.validateFields().then(vaild => {
      if (vaild) {
        const params = {
          ...form.getFieldsValue()
        }
        console.log(params)
        if (action === 'create') {
          createDept(params).then(() => {
            message.success('创建成功')
            props.update()
          })
        } else {
          editDept(params).then(() => {
            message.success('修改成功')
            props.update()
          })
        }
        onCancel()
      }
    })
  }

  // 关闭
  const onCancel = () => {
    setVisiable(false)
    form.resetFields()
  }

  return (
    <Modal
      title={action === 'edit' ? '编辑部门' : '创建部门'}
      width={800}
      okText='确定'
      cancelText='取消'
      open={visiable}
      onCancel={onCancel}
      onOk={handleSubmit}
    >
      <Form form={form} labelAlign='right' labelCol={{ span: 4 }}>
        <Form.Item hidden name='_id'>
          <Input />
        </Form.Item>
        <Form.Item label='上级部门' name='parentId'>
          <TreeSelect
            placeholder='请选择上级部门'
            allowClear
            treeDefaultExpandAll
            fieldNames={{ label: 'deptName', value: '_id' }}
            treeData={deptList}
          ></TreeSelect>
        </Form.Item>
        <Form.Item label='部门名称' name='deptName' rules={[{ required: true, message: '请输入部门名称' }]}>
          <Input></Input>
        </Form.Item>
        <Form.Item label='负责人' name='userName' rules={[{ required: true, message: '请输入部门名称' }]}>
          <Select>
            {userList.length &&
              userList.map(item => (
                <Select.Option value={item.userName} key={item.userId}>
                  {item.userName}
                </Select.Option>
              ))}
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default CreateDept
